<template>
  <a-modal
      title="报价单详情"
      :open="visible"
      :footer="null"
      @cancel="handleCancel"
      width="800px"
  >
    <a-descriptions :column="2" bordered size="small" class="quote-detail">
      <a-descriptions-item label="报价单号" :span="1">{{ quote?.quoteNo }}</a-descriptions-item>
      <a-descriptions-item label="状态" :span="1">
        <a-tag :color="getStatusColor(quote?.status || 0)">
          {{ getStatusLabel(quote?.status || 0) }}
        </a-tag>
      </a-descriptions-item>
      <a-descriptions-item label="客户名称" :span="1">{{ quote?.customerName }}</a-descriptions-item>
      <a-descriptions-item label="销售人员" :span="1">{{ quote?.salesPerson }}</a-descriptions-item>
      <a-descriptions-item label="创建时间" :span="1">{{ formatDate(quote?.createTime) }}</a-descriptions-item>
      <a-descriptions-item label="更新时间" :span="1">{{ formatDate(quote?.updateTime) }}</a-descriptions-item>
      <a-descriptions-item label="备注" :span="2">{{ quote?.remarks || '无' }}</a-descriptions-item>
    </a-descriptions>

    <a-divider orientation="left">产品明细</a-divider>
    <a-table
        :data-source="quote?.items || []"
        :pagination="false"
        :row-key="(record: any) => record.itemId"
        size="small"
        class="quote-items-table"
    >
      <a-table-column title="产品名称" data-index="productName"/>
      <a-table-column title="单价" data-index="unitPrice">
        <template #default="{ text }">¥{{ formatCurrency(text) }}</template>
      </a-table-column>
      <a-table-column title="数量" data-index="quantity"/>
      <a-table-column title="小计" data-index="totalPrice">
        <template #default="{ text }">¥{{ formatCurrency(text) }}</template>
      </a-table-column>
      <a-table-column title="备注" data-index="remarks">
        <template #default="{ text }">{{ text || '无' }}</template>
      </a-table-column>
    </a-table>

    <a-divider/>
    <div class="quote-summary">
      <div class="summary-item">
        <span class="label">总价：</span>
        <span class="value">¥{{ formatCurrency(quote?.totalAmount) }}</span>
      </div>
      <div class="summary-item">
        <span class="label">优惠金额：</span>
        <span class="value">¥{{ formatCurrency(quote?.discountAmount) }}</span>
      </div>
      <div class="summary-item final-amount">
        <span class="label">最终金额：</span>
        <span class="value">¥{{ formatCurrency(quote?.finalAmount) }}</span>
      </div>
    </div>

    <div class="action-btns">
      <a-button @click="handleCancel">关闭</a-button>
      <a-button type="primary" v-if="quote?.status === 1 || quote?.status === 4" @click="handleEdit">编辑</a-button>
      <a-button type="primary" v-if="quote?.status === 1 || quote?.status === 4" @click="handleSubmit">提交审核
      </a-button>
      <a-button type="primary" v-if="quote?.status === 2" @click="handleReceive">接收</a-button>
      <a-button danger v-if="quote?.status === 2" @click="handleReject">拒绝</a-button>
      <a-button @click="handlePrint">导出PDF</a-button>
    </div>

    <!-- 隐藏的打印视图，用于PDF导出 -->
    <div class="print-container"
         style="position: fixed; left: -9999px; top: 0; z-index: -1; opacity: 0; pointer-events: none;">
      <QuotePrintView ref="printViewRef" :quote="quote"/>
    </div>
  </a-modal>
</template>

<script setup lang="ts">
import {defineEmits, defineProps, ref, withDefaults} from 'vue'
import {message} from 'ant-design-vue'
import type {Quote} from '@/types/quote'
import {quoteStatusOptions} from '@/types/quote'
import {usePermission} from '@/composables/usePermission'
import * as quoteApi from '@/api/quote'
import {formatCurrency} from '@/utils/format'
import jsPDF from 'jspdf'
import html2canvas from 'html2canvas'
import QuotePrintView from './QuotePrintView.vue'

interface Props {
  visible: boolean
  quoteId?: number
  quote?: Quote
}

interface Emits {
  (e: 'update:visible', visible: boolean): void

  (e: 'success'): void

  (e: 'edit', quote: Quote): void
}

const props = withDefaults(defineProps<Props>(), {
  quoteId: undefined,
  quote: undefined
})

const emit = defineEmits<Emits>()

// 使用usePermission但不做按钮级权限控制
const {checkPermission} = usePermission()

// 格式化日期
const formatDate = (date: Date | string | undefined) => {
  if (!date) return '-'
  if (typeof date === 'string') {
    return date
  }
  return date.toLocaleString()
}

// 获取状态标签
const getStatusLabel = (status: number) => {
  const option = quoteStatusOptions.find(item => item.value === status)
  return option?.label || '未知'
}

// 获取状态颜色
const getStatusColor = (status: number) => {
  const option = quoteStatusOptions.find(item => item.value === status)
  return option?.color || 'default'
}

// 取消
const handleCancel = () => {
  emit('update:visible', false)
}

// 编辑报价单
const handleEdit = () => {
  if (!props.quote) return
  emit('edit', props.quote)
  handleCancel()
}

// 提交审核
const handleSubmit = async () => {
  if (!props.quote) return
  try {
    await quoteApi.submitQuote(props.quote.quoteId)
    message.success('提交成功')
    emit('success')
    handleCancel()
  } catch (error) {
    message.error('提交失败')
  }
}

// 接收报价单
const handleReceive = async () => {
  if (!props.quote) return
  try {
    await quoteApi.receiveQuote(props.quote.quoteId)
    message.success('接收成功')
    emit('success')
    handleCancel()
  } catch (error) {
    message.error('接收失败')
  }
}

// 拒绝报价单
const handleReject = async () => {
  if (!props.quote) return
  try {
    await quoteApi.rejectQuote(props.quote.quoteId)
    message.success('拒绝成功')
    emit('success')
    handleCancel()
  } catch (error) {
    message.error('拒绝失败')
  }
}

// 打印视图引用
const printViewRef = ref<InstanceType<typeof QuotePrintView>>()

// 导出PDF
const handlePrint = async () => {
  if (!props.quote) {
    message.warning('报价单数据不存在')
    return
  }

  try {
    const loadingMessage = message.loading('正在生成PDF...', 0)

    // 等待DOM更新，确保打印视图已渲染
    await new Promise(resolve => setTimeout(resolve, 500))

    // 获取打印视图的DOM元素
    const printView = printViewRef.value
    if (!printView) {
      loadingMessage()
      message.error('无法获取打印视图')
      console.error('printViewRef.value is null')
      return
    }

    const element = printView.printContent
    if (!element) {
      loadingMessage()
      message.error('无法获取打印内容')
      console.error('printContent is null')
      return
    }

    console.log('准备捕获元素:', element, '元素尺寸:', element.offsetWidth, element.offsetHeight)

    // 获取父容器
    const container = element.parentElement
    const originalContainerStyle = container ? {
      position: container.style.position,
      left: container.style.left,
      top: container.style.top,
      zIndex: container.style.zIndex,
      opacity: container.style.opacity,
      pointerEvents: container.style.pointerEvents
    } : null

    // 临时显示元素以便html2canvas捕获
    const originalElementStyle = {
      position: element.style.position,
      left: element.style.left,
      top: element.style.top,
      zIndex: element.style.zIndex,
      opacity: element.style.opacity,
      visibility: element.style.visibility,
      display: element.style.display
    }

    // 临时显示容器和元素
    if (container) {
      container.style.position = 'fixed'
      container.style.left = '0'
      container.style.top = '0'
      container.style.zIndex = '9999'
      container.style.opacity = '1'
      container.style.pointerEvents = 'none'
    }

    element.style.position = 'relative'
    element.style.left = 'auto'
    element.style.top = 'auto'
    element.style.zIndex = '9999'
    element.style.opacity = '1'
    element.style.visibility = 'visible'
    element.style.display = 'block'

    // 等待样式应用和内容渲染
    await new Promise(resolve => setTimeout(resolve, 300))

    console.log('元素渲染后尺寸:', element.offsetWidth, element.offsetHeight, element.scrollWidth, element.scrollHeight)

    // 使用html2canvas将HTML转换为canvas，提高清晰度
    const canvas = await html2canvas(element, {
      scale: 3, // 提高清晰度到3倍
      useCORS: true,
      logging: false,
      backgroundColor: '#ffffff',
      allowTaint: true,
      width: element.scrollWidth || element.offsetWidth,
      height: element.scrollHeight || element.offsetHeight
    })

    console.log('Canvas尺寸:', canvas.width, canvas.height)

    // 恢复原始样式
    if (container && originalContainerStyle) {
      container.style.position = originalContainerStyle.position
      container.style.left = originalContainerStyle.left
      container.style.top = originalContainerStyle.top
      container.style.zIndex = originalContainerStyle.zIndex
      container.style.opacity = originalContainerStyle.opacity
      container.style.pointerEvents = originalContainerStyle.pointerEvents
    }

    element.style.position = originalElementStyle.position
    element.style.left = originalElementStyle.left
    element.style.top = originalElementStyle.top
    element.style.zIndex = originalElementStyle.zIndex
    element.style.opacity = originalElementStyle.opacity
    element.style.visibility = originalElementStyle.visibility
    element.style.display = originalElementStyle.display

    // 检查canvas是否有内容
    if (canvas.width === 0 || canvas.height === 0) {
      loadingMessage()
      message.error('无法捕获内容，请检查控制台日志')
      console.error('Canvas为空，宽度:', canvas.width, '高度:', canvas.height)
      return
    }

    // 计算PDF尺寸（A4纸：210mm x 297mm）
    const imgWidth = 210 // A4宽度（mm）
    const imgHeight = (canvas.height * imgWidth) / canvas.width
    const pdf = new jsPDF('p', 'mm', 'a4')

    // 计算页数，避免生成空白页
    const pageHeight = 297 // A4高度（mm）
    const pageWidth = 210 // A4宽度（mm）

    // 如果内容高度小于等于一页，直接添加
    if (imgHeight <= pageHeight) {
      pdf.addImage(canvas.toDataURL('image/png', 1.0), 'PNG', 0, 0, imgWidth, imgHeight)
    } else {
      // 内容超过一页，需要分页
      let heightLeft = imgHeight
      let position = 0
      let pageCount = 0

      // 添加第一页
      pdf.addImage(canvas.toDataURL('image/png', 1.0), 'PNG', 0, position, imgWidth, imgHeight)
      heightLeft -= pageHeight
      pageCount++

      // 如果还有剩余内容，添加新页
      while (heightLeft > 0 && pageCount < 10) { // 限制最多10页，防止无限循环
        position = -(pageCount * pageHeight) // 负值表示向上移动
        pdf.addPage()
        pdf.addImage(canvas.toDataURL('image/png', 1.0), 'PNG', 0, position, imgWidth, imgHeight)
        heightLeft -= pageHeight
        pageCount++
      }
    }

    // 生成文件名
    const fileName = `报价单_${props.quote.quoteNo}_${new Date().getTime()}.pdf`

    // 保存PDF
    pdf.save(fileName)

    loadingMessage()
    message.success('PDF导出成功')
  } catch (error) {
    message.destroy()
    message.error('PDF导出失败：' + (error instanceof Error ? error.message : '未知错误'))
    console.error('PDF导出失败:', error)
  }
}
</script>

<style scoped>
.quote-detail {
  margin-bottom: 20px;
}

.quote-items-table {
  margin: 16px 0;
}

.quote-summary {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  margin-top: 16px;
}

.summary-item {
  margin-bottom: 8px;
  font-size: 14px;
}

.summary-item .label {
  font-weight: bold;
  margin-right: 8px;
}

.summary-item .value {
  min-width: 80px;
  display: inline-block;
  text-align: right;
}

.final-amount {
  font-size: 16px;
  color: #ff4d4f;
  font-weight: bold;
}

.action-btns {
  margin-top: 24px;
  text-align: right;
}

.action-btns button {
  margin-left: 8px;
}
</style>